package com.gexin.controller.system.advertising;

import com.gexin.core.web.SystemBaseController;
import com.gexin.model.config.Advertising;
import com.gexin.model.product.Products;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 黎峻
 * @Title: 广告位
 * @date 2019/10/2816:00
 */
@ControllerBind(controllerKey = "/system/advertising", viewPath = "WEB-INF/system/advertising")
public class AdvertisingController extends SystemBaseController {
	private static Log log = Log.getLog(AdvertisingController.class);

	public void index(){
		setAttr("product_list", JsonKit.toJson(Products.dao.getProductsByAttrType(1)));
		render("advertising_list.html");
	}

	public void loadPageData(){
		Advertising advertising =new Advertising();
		advertising.setProductId(getParaToInt("product_id"));
		advertising.setStatus(getParaToInt("state"));
		success(Advertising.dao.query(getpage(),getpageSize(),advertising));
	}

	public void save(){
		Advertising a =getModel(Advertising.class,"a");
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date_time=getPara("date_time");
		if(StringUtils.isEmpty(date_time)){
			fail("请选择时间范围");
			return;
		}
		try {
			String [] date=date_time.split(" - ");
			a.setStartTime(sdf.parse(date[0]));
			a.setEndTime(sdf.parse(date[1]));
		}catch (Exception e){
			e.printStackTrace();
			log.error("保存广告位时间格式错误！时间："+date_time);
			fail("抱歉，时间范围格式不正确");
			return;
		}
		a.setStatus(DateOnStatus(a.getStartTime(),a.getEndTime()));
		if(a.getId()==null){
			a.save();
			success("添加成功");
			return ;
		}else{
			a.update();
			success("修改成功");
			return ;
		}
	}

	public void delete_ad(){
		Advertising.dao.deleteById(getPara("id"));
		success("删除成功");
	}


	/**
	 * 根据开始时间和结束时间返回对应的状态
	 * @return 0 未开始 1 进行中 2 结束
	 *  现在返回  ： 0 未上线  1 上线中  2 已下线
	 */
	public int DateOnStatus(Date start, Date end){
		Date now =new Date();
		long nowTime=now.getTime();
		long startTime=start.getTime();
		long endTime=end.getTime();
		if(nowTime>start.getTime() && nowTime>endTime){
			return 2;
		}else if(start.getTime()>nowTime && endTime>nowTime){
			return 0;
		}else{
			return 1;
		}
	}

}
